package com.hmall.item.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;


    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list")
    public PageDTO<Item> listPage(@RequestParam("page") Integer page, @RequestParam("size") Integer size) {

        Page pageInfo = new Page(page, size);

        Page<Item> page1 = itemService.page(pageInfo);

        return new PageDTO<>(page1.getTotal(),page1.getRecords());
    }


    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public Item queryItemById(@PathVariable("id") Long id) {
        return itemService.getById(id);
    }


    /**
     * 新增商品
     * @param item
     */
    @PostMapping
    public void saveItem(@RequestBody Item item) {
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        itemService.save(item);
    }


    /**
     * 更新上下架状态
     * @param id
     * @param status
     */
    @PutMapping("/status/{id}/{status}")
    public void updateStatus(@PathVariable("id") Long id,
                                 @PathVariable("status") Integer status){
        itemService.updateItem(id, status);
    }

    @PutMapping
    public void updateItem(@RequestBody Item item) {
        item.setUpdateTime(new Date());
        item.setStatus(null);
        itemService.updateById(item);
    }

    @DeleteMapping("{id}")
    public void deleteItemById(@PathVariable("id") Long id) {
        itemService.removeById(id);
    }

}
